package repository

import (
	"fmt"
	"gorm.io/gorm"
	"sync"
)

type Post struct {
	Id         int64  `gorm:"column:id"`
	UserId     int64  `gorm:"column:user_id"`
	TopicId    int64  `gorm:"column:topic_id"`
	RootId     int    `gorm:"column:root_id"`
	Content    string `gorm:"column:content"`
	Likes      int64  `gorm:"column:likes;default:0"`
	CreateTime int64  `gorm:"autoUpdateTime:milli"`
}

func (Post) TableName() string {
	return "post"
}

type PostDao struct {
}

var (
	postDao  *PostDao
	postOnce sync.Once
)

func NewPostDaoInstance() *PostDao {
	postOnce.Do(
		func() {
			postDao = &PostDao{}
		})
	return postDao
}

func (*PostDao) QueryPostById(id int64) (*Post, error) {
	var post Post
	err := db.Find(&post, id).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	if err != nil {
		fmt.Println(err)
		return nil, err
	}
	return &post, nil
}

func (*PostDao) QueryPostByTopicId(topicId int64) ([]*Post, error) {
	var posts []*Post
	err := db.Where("topic_id = ?", topicId).Find(&posts).Error
	if err != nil {
		fmt.Println("find posts by topicId err:" + err.Error())
		return nil, err
	}
	return posts, nil
}

func (*PostDao) CreatePost(post *Post) error {
	if err := db.Create(post).Error; err != nil {
		fmt.Println("create post err:" + err.Error())
		return err
	}
	return nil
}
